package com.cskaoyan.controller.auth.wxauth;

import com.cskaoyan.bean.MallUser;
import com.cskaoyan.model.vo.BaseRespVo;
import com.cskaoyan.model.vo.auth.AdminInfoBean;
import com.cskaoyan.model.vo.auth.LoginUserData;
import com.cskaoyan.model.vo.auth.wx.WxUserData;
import com.cskaoyan.model.vo.auth.wx.WxUserInfo;
import com.cskaoyan.service.auth.wxuser.WxAuthService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.UUID;

/**
 * @program: project-market
 * @description: 微信端用户登入登出
 * @author: Jesson Guo
 * @create: 2021-12-02 19:31
 **/
@RequestMapping("wx/auth")
@RestController
public class WxAuthController {
    @Autowired
    WxAuthService userService;

    //用户登录
    @PostMapping("login")
    public BaseRespVo wxAuthLogin(@RequestBody MallUser wxUserLoginBO, HttpServletRequest request) {


        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String sessionId = (String) session.getId();

        wxUserLoginBO.setSessionKey(sessionId);//令牌
        wxUserLoginBO.setLastLoginIp(request.getRemoteAddr());//登录端ip地址
        // 查出mallUser
        MallUser mallUser = userService.wxAuthLogin(wxUserLoginBO);

        if (mallUser != null) {

            String username = mallUser.getUsername();
            Integer uid = mallUser.getId();
            String password = mallUser.getPassword();

            subject.login(new UsernamePasswordToken(username, password));

            session.setAttribute("username", username);
            session.setAttribute("uid", uid);

            return succeed(sessionId, mallUser);
        }

        return BaseRespVo.manual(700, "账号不存在", null);
    }


    private BaseRespVo succeed(String sessionId, MallUser mallUser) {


        WxUserData wxUserData = new WxUserData();
        WxUserInfo wxUserInfo = new WxUserInfo();

        wxUserInfo.setAvatarUrl(mallUser.getAvatar());
        wxUserInfo.setNickName(mallUser.getNickname());

        wxUserData.setUserInfo(wxUserInfo);
        wxUserData.setToken(sessionId);

        return BaseRespVo.ok(wxUserData);
    }


    @PostMapping("logout")
    public BaseRespVo wxAuthLogout(HttpSession session) {
        session.removeAttribute("username");
        session.removeAttribute("token");
        session.removeAttribute("uid");
        return BaseRespVo.ok();
    }

}
